package com.rc.evcharger.biz.notify;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dozermapper.core.Mapper;
import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.mq.MqConfig;
import com.rc.evcharger.common.mq.MqProducer;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.hlht.HlhtOrderInfo;
import com.rc.evcharger.model.hlhtsk.HlhtskTenant;
import com.rc.evcharger.model.order.OrderComment;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.service.elec.ElecGunService;
import com.rc.evcharger.service.hlht.HlhtOrderInfoService;
import com.rc.evcharger.service.hlhtsk.HlhtskTenantService;
import com.rc.evcharger.service.order.OrderCommentService;
import com.rc.evcharger.service.order.OrderInfoService;
import com.rc.evcharger.vo.charge.CommandStartReq;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 推送订单启动状态，不管成功与否都会推送
 * 6.5 notification_start_charge_result
 * 推送订单启动充电的结果给OPEN应用层
 * Create by Yang on 2019/1/17
 */
@Component
public class NotifyStartChargeResult {
    private static Logger logger = LogManager.getLogger(NotifyStartChargeResult.class);

    @Autowired
    private MqProducer mqProducer;

    //@Autowired
    //private CmdMqProducer mqProducer;

    @Autowired
    private Mapper dozerMapper;

    //@Autowired
    //private TenantService tenantService;

    @Autowired
    private HlhtskTenantService hlhtskTenantService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderCommentService orderCommentService;

    @Autowired
    private HlhtOrderInfoService hlhtOrderInfoService;

    /**
     * 推送订单启动状态
     *
     * @param orderNum
     * @param status
     */
    public void notifyOrderStart(String orderNum, Integer status) {
        CommandStartReq commandStartReq = new CommandStartReq();
        commandStartReq.setStatus(status);//订单启动状态 0.启动成功 1.启动失败

        if (status == SocketConstant.CON1) { //启动失败
            OrderComment orderComment = orderCommentService.selectByOrderNum(orderNum);

            commandStartReq.setTenantCode(orderComment.getTenantCode());
            commandStartReq.setTenantOperatorCode(orderComment.getTenantOperatorCode());
            commandStartReq.setHlhtTenantCode(orderComment.getHlhtTenantCode());
            commandStartReq.setHlhtOperatorId(orderComment.getHlhtOperatorId());

            commandStartReq.setMemberId(orderComment.getMemberId());

            //commandStopReq.setOrderId(String.valueOf(order.getOrderId()));
            commandStartReq.setOutOrderNum(orderComment.getOutOrderNum());
            commandStartReq.setOrderNum(orderComment.getOrderNum());

            ElecGun elecGun = elecGunService.selectByPrimaryKey(orderComment.getElecGunId());
            commandStartReq.setGunNo(elecGun.getGunNo());

            commandStartReq.setElecStationId(orderComment.getElecStationId());
            commandStartReq.setElecPileId(orderComment.getElecPileId());
            commandStartReq.setElecGunId(orderComment.getElecGunId());

            //发送启动失败回调消息
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String enData = objectMapper.writeValueAsString(commandStartReq);
                mqProducer.send(MqConfig.CALLBACK_START_CHARGE_RESULT, enData);

                logger.warn("notification_start_charge_result 启动充电失败，订单:{}", orderNum);
            } catch (JsonProcessingException e) {
                logger.error("notification_start_charge_result 启动充电失败推送出错了", e);
            }
        } else { //启动成功
            OrderInfo orderInfo = orderInfoService.selectByOrderNum(orderNum);
            ElecGun elecGun = elecGunService.selectByPrimaryKey(orderInfo.getElecGunId());

            commandStartReq.setTenantCode(orderInfo.getTenantCode());
            commandStartReq.setTenantOperatorCode(orderInfo.getTenantOperatorCode());
            commandStartReq.setHlhtTenantCode(orderInfo.getHlhtTenantCode());
            commandStartReq.setHlhtOperatorId(orderInfo.getHlhtOperatorId());

            commandStartReq.setMemberId(orderInfo.getMemberId());

            commandStartReq.setOrderSource(orderInfo.getOrderSource());
            commandStartReq.setOrderId(orderInfo.getOrderId());
            commandStartReq.setOutOrderNum(orderInfo.getOutOrderNum());
            commandStartReq.setOrderNum(orderInfo.getOrderNum());
            commandStartReq.setGunNo(elecGun.getGunNo());

            commandStartReq.setElecStationId(orderInfo.getElecStationId());
            commandStartReq.setElecPileId(orderInfo.getElecPileId());
            commandStartReq.setElecGunId(orderInfo.getElecGunId());

            try {
                //发送启动成功回调消息
                ObjectMapper objectMapper = new ObjectMapper();
                String enData = objectMapper.writeValueAsString(commandStartReq);
                mqProducer.sendDelay(MqConfig.CALLBACK_START_CHARGE_RESULT, enData, 1000);

                logger.info("启动成功，notification_start_charge_result 推送完成，对应的订单号:{},外部订单号:{},对应的ordersource:{}",
                        orderInfo.getOrderNum(), orderInfo.getOutOrderNum(), orderInfo.getOrderSource());

                //启动成功时增加对方的互联订单
                saveStartHlhtOrderInfo(commandStartReq, orderInfo);
            } catch (Exception e) {
                logger.error("notification_start_charge_result 推送出错了，对应的订单号:" + orderInfo.getOrderNum(), e);
            }
        }
    }

    /**
     * 互联互通启动成功时保存推送信息
     * @param orderInfo
     */
    //private void saveHlhtOrderNotify(OrderInfo orderInfo) {
    //    //如果是互联互通启动的订单就记录推送等信息
    //    if (StringUtils.isNotBlank(orderInfo.getHlhtOperatorId())) {
    //        HlhtTenantOrderNotify hlhtOrderNotify = new HlhtTenantOrderNotify();
    //        hlhtOrderNotify.setTenantCode(orderInfo.getTenantCode());
    //        hlhtOrderNotify.setTenantOperatorCode(orderInfo.getTenantOperatorCode());
    //        hlhtOrderNotify.setHlhtOperatorId(orderInfo.getHlhtOperatorId());
    //
    //        hlhtOrderNotify.setOrderId(orderInfo.getOrderId());
    //        hlhtOrderNotify.setOrderNum(orderInfo.getOrderNum());
    //        hlhtOrderNotify.setOutOrderNum(orderInfo.getOutOrderNum());
    //        hlhtOrderNotify.setMemberId(orderInfo.getMemberId());
    //        hlhtOrderNotify.setStartChargeReqTime(orderInfo.getCreatedTime());
    //        hlhtTenantOrderNotifyService.insertSelective(hlhtOrderNotify);
    //    }
    //}

    /**
     * 内联其它SAAS运营商桩时,增加对方的互联订单
     */
    private void saveStartHlhtOrderInfo(CommandStartReq commandStartReq, OrderInfo orderInfo) {
        //内联其它SAAS运营商桩时,增加对方的互联订单单
        if (StringUtils.isNotBlank(commandStartReq.getHlhtTenantCode())) {
            //orderInfo转换HlhtOrderInfo
            HlhtOrderInfo newHlhtOrderInfo = dozerMapper.map(orderInfo, HlhtOrderInfo.class);

            //hlht_member_id:互联会员ID,属于tenant_code（由瑞晨平台方审核通过时自动创建，这个用户不能登录）,代表hlht_tenant_code,内部互联时需要
            if (!commandStartReq.getTenantCode().equals(commandStartReq.getHlhtTenantCode())) {
                if (!commandStartReq.getOrderSource().equals("9")) {//SAAS运营商APP或公众号生产的订单

                    //以下字段要反过来:内联正向+内联反向
                    newHlhtOrderInfo.setTenantCode(commandStartReq.getHlhtTenantCode());
                    newHlhtOrderInfo.setHlhtTenantCode(commandStartReq.getTenantCode());
                    newHlhtOrderInfo.setHlhtOrderType("1");//互联互通订单类型以tenant_code为基准,0为自主订单 1反向对接订单 2正向对接订单, 默认0

                    //互联用户ID
                    //Tenant tenant = tenantService.selectByPrimaryKey(commandStartReq.getTenantCode());
                    //newHlhtOrderInfo.setMemberId(tenant.getMemberId());

                    //hlhtsk_tenant.hlht_member_id:互联会员ID,属于tenant_code（由瑞晨平台方审核通过时自动创建，这个用户不能登录）,代表hlht_tenant_code,内部互联时需要
                    //按设备商+运营商查找
                    //tenantCode  设备方运营商
                    //hlhtTenantCode SAAS内互联互通时对方运营商
                    HlhtskTenant hlhtskTenant = hlhtskTenantService.selectHlhtTenantCode(commandStartReq.getHlhtTenantCode(), commandStartReq.getTenantCode());
                    newHlhtOrderInfo.setMemberId(hlhtskTenant.getHlhtMemberId());

                    hlhtOrderInfoService.insertSelective(newHlhtOrderInfo);
                } else {//第三方API生产的订单
                    //以下字段要反过来:外联反向/内联反向
                    newHlhtOrderInfo.setTenantCode(commandStartReq.getHlhtTenantCode());
                    newHlhtOrderInfo.setHlhtTenantCode(commandStartReq.getTenantCode());
                    newHlhtOrderInfo.setHlhtOrderType("1");//互联互通订单类型以tenant_code为基准,0为自主订单 1反向对接订单 2正向对接订单, 默认0

                    //互联用户ID
                    //Tenant tenant = tenantService.selectByPrimaryKey(commandStartReq.getTenantCode());
                    //newHlhtOrderInfo.setMemberId(tenant.getMemberId());

                    //hlhtsk_tenant.hlht_member_id:互联会员ID,属于tenant_code（由瑞晨平台方审核通过时自动创建，这个用户不能登录）,代表hlht_tenant_code,内部互联时需要
                    //按设备商+运营商查找
                    //tenantCode  设备方运营商
                    //hlhtTenantCode SAAS内互联互通时对方运营商
                    HlhtskTenant hlhtskTenant = hlhtskTenantService.selectHlhtTenantCode(commandStartReq.getHlhtTenantCode(), commandStartReq.getTenantCode());
                    newHlhtOrderInfo.setMemberId(hlhtskTenant.getHlhtMemberId());

                    hlhtOrderInfoService.insertSelective(newHlhtOrderInfo);
                }
            }
        }
    }
}
